package com.zzl.alligator.management.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.zzl.alligator.common.constant.SystemConstants;
import com.zzl.alligator.common.util.SecurityUtils;
import com.zzl.alligator.common.util.StringUtils;
import com.zzl.alligator.framework.base.controller.BaseController;
import com.zzl.alligator.framework.support.web.vo.JsonResult;
import com.zzl.alligator.framework.support.web.vo.TreeSelect;
import com.zzl.alligator.management.system.domain.SysDept;
import com.zzl.alligator.management.system.domain.SysUser;
import com.zzl.alligator.management.system.service.ISysDeptService;
import com.zzl.alligator.management.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 部门
 *
 * @author zhouziliang
 * @since 2020/6/29
 */
@RestController
@RequestMapping("/system/dept")
@Slf4j
public class SysDeptController extends BaseController {

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;
    /**
     * 查询列表
     *
     * @param dept 查询个条件
     * @return 结果
     */
    @GetMapping
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    public JsonResult listDept(SysDept dept) {
        List<SysDept> deptList = sysDeptService.findDeptList(dept);
        return JsonResult.success(deptList);
    }

    /**
     * 查询部门列表（排除节点）
     *
     * @param deptId 待排除的节点ID
     * @return 列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public JsonResult findDeptListExcludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> deptList = sysDeptService.findDeptList(new SysDept());
        if (deptList == null) {
            return JsonResult.success();
        }
        List<SysDept> collect = deptList.stream().filter(dept ->
                !dept.getParentId().equals(deptId)
                        && !ArrayUtil.contains(StringUtils.split(dept.getAncestors(), ","), deptId)
        ).collect(Collectors.toList());

        return JsonResult.success(collect);
    }


    /**
     * 根据部门编号获取详细信息
     *
     * @param deptId id
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public JsonResult getInfo(@PathVariable Long deptId) {
        return JsonResult.success(sysDeptService.findDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     *
     * @param dept 条件
     * @return 结果
     */
    @GetMapping("/treeselect")
    public JsonResult treeselect(SysDept dept) {
        List<SysDept> depts = sysDeptService.findDeptList(dept);
        return JsonResult.success(sysDeptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     *
     * @param roleId id
     * @return 结果
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public JsonResult roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysDept> depts = sysDeptService.findDeptList(new SysDept());
        Map<String, Object> map = new HashMap<>(2);
        map.put("checkedKeys", sysDeptService.findDeptListByRoleId(roleId));
        map.put("depts", sysDeptService.buildDeptTreeSelect(depts));
        return JsonResult.success(map);
    }

    /**
     * 新增部门
     *
     * @param dept 部门
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @PostMapping
    public JsonResult add(@Validated @RequestBody SysDept dept) {
        if (SystemConstants.NOT_UNIQUE.equals(sysDeptService.checkDeptNameUnique(dept))) {
            return JsonResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(sysDeptService.insertDept(dept));
    }

    /**
     * 修改部门
     *
     * @param dept 部门
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @PutMapping
    public JsonResult edit(@Validated @RequestBody SysDept dept) {
        if (SystemConstants.NOT_UNIQUE.equals(sysDeptService.checkDeptNameUnique(dept))) {
            return JsonResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return JsonResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(SystemConstants.DEPT_DISABLE, dept.getStatus())
                && sysDeptService.findNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return JsonResult.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sysDeptService.updateDept(dept));
    }

    /**
     * 删除部门
     *
     * @param deptId id
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @DeleteMapping("/{deptId}")
    public JsonResult remove(@PathVariable Long deptId) {
        if (sysDeptService.hasChildByDeptId(deptId)) {
            return JsonResult.error("存在下级部门,不允许删除");
        }
        if (sysDeptService.checkDeptExistUser(deptId)) {
            return JsonResult.error("部门存在用户,不允许删除");
        }
        return toAjax(sysDeptService.deleteDeptById(deptId));
    }


    /**
     * 根据部门ID，获取子节点的信息
     *
     * @param deptId 父部门的id
     * @return 子节点信息
     */
    @GetMapping("/deptuser/{deptId}")
    public JsonResult findRootDept(@PathVariable Long deptId) {
        log.info("父节点信息");
        List<SysDept> list = sysDeptService.findDeptListByParentId(deptId);
        List<SysUser> users = sysUserService.findUserByDeptId(deptId);
        List<TreeSelect> res = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(users)) {
            users.forEach(user -> {
                TreeSelect node = new TreeSelect();
                node.setLabel(user.getUserName());
                node.setId(user.getUserId());
                node.setLeaf(true);
                res.add(node);
            });
        }
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(dept -> {
                TreeSelect node = new TreeSelect();
                node.setLabel(dept.getDeptName());
                node.setId(dept.getDeptId());
                node.setLeaf(false);
                res.add(node);
            });
        }

        return JsonResult.success(res);
    }


    /**
     * 根据部门ID，获取子节点的信息
     *
     * @return 子节点信息
     */
    @GetMapping("/deptuser")
    public JsonResult findDeptUserTreeSelect() {
        List<SysDept> depts = sysDeptService.findDeptList(new SysDept());
        List<SysUser> users = sysUserService.findUserList(new SysUser());
        return JsonResult.success(sysDeptService.buildDeptUserTreeSelect(depts, users));

    }
}
